package com.mango.module.util;

import java.util.Base64;

import lombok.extern.slf4j.Slf4j;

/**
 * md5(base64)
 * @author Mango-Lab
 * @Date 2021年4月8日
 */
@Slf4j
public class MD5Base64 {
	
	/**
	 * 编码
	 * @param password
	 * @return
	 */
	public static String ldapMd5EncodePassword(String password) {
		byte[] unencodedPassword = password.getBytes();
		java.security.MessageDigest md = null;
		try {
			md = java.security.MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			log.error("Exception: " + e);
			return password;
		}
		md.reset();
		md.update(unencodedPassword);
		byte[] encodedPassword = md.digest();
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				buf.append("0");
			}
			buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}

		String standardMd5 = buf.toString();
		byte[] ba = new byte[standardMd5.length() / 2];
		for (int i = 0; i < standardMd5.length(); i = i + 2) {
			ba[i == 0 ? 0 : i / 2] = (byte) (0xff & Integer.parseInt(standardMd5.substring(i, i + 2), 16));
		}
		return "{MD5}" + Base64.getEncoder().encodeToString(ba);
	}
	
	/**
	 * 解码
	 * @param password
	 * @return
	 */
	public static String ldapMd5DecodePassword(String password) {
		int index=password.indexOf("}");
		if(index==-1) {
			return password;
		}
		String newPwd=password.substring(index+1);
		byte[] bytes=Base64.getDecoder().decode(newPwd);
		return bytesToHexString(bytes);
	}
	
	/** 
	 * byte数组转16进制字符串    
	 * @param src
	 * @return
	 */
	private static String bytesToHexString(byte[] src){   
	    StringBuilder stringBuilder = new StringBuilder("");   
	    if (src == null || src.length <= 0) {   
	        return null;   
	    }   
	    for (int i = 0; i < src.length; i++) {   
	        int v = src[i] & 0xFF;   
	        String hv = Integer.toHexString(v);   
	        if (hv.length() < 2) {   
	            stringBuilder.append(0);   
	        }   
	        stringBuilder.append(hv);   
	    }   
	    return stringBuilder.toString();   
	}
}
